package com.browsesoft.user;

import java.io.Serializable;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.EntityManager;
import com.browsesoft.ExtendElement;
import com.browsesoft.ManagerGroup;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLFormModel;
import com.browsesoft.resource.BasicResource;
import com.browsesoft.resource.Resource;

/**
 * 角色
 */
public class Role extends BasicResource implements HTMLFormModel, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2764319003638662529L;

	// /**
	// * 拥有该角色的用户
	// */
	// private LinkedList users = new LinkedList();
	//
	// private LinkedList US = new LinkedList();

	/**
	 * 角色所拥有的功能列表
	 */
	private LinkedList functions = new LinkedList();

	/**
	 * 父ID
	 */
	private transient HTMLBasicComponent component = null;

	private String action = null;

	/**
	 * 默认构造函数
	 */
	public Role() {
		super();
		// 资源类型
		this.attributes.put("resourcetype", "role");
	}
	
	public void setParentID(String parentID) {
		this.parentID = parentID;
	}
	/**
	 * 初始化model
	 * 
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
		parentID = request.getParameter("parentid");
		templateName = request.getParameter("templatename");
		this.setTemplateName(templateName);
	}

	/**
	 * 使用属性构造
	 */
	public Role(Hashtable attrs) throws Exception {
		super(attrs);
	}

	/**
	 * 添加角色属性
	 * 
	 */
	public void updateAttributes(Hashtable attrs) throws Exception {
		// 如果应该插入
		if (isShouldInsert()) {
			// 放入图标
			this.attributes.put("f_icon", "tree_role");
			this.getAttributes().putAll(attrs);
			insert();
			EntityManager entitymanager = (EntityManager) ManagerGroup
					.getManagerGroup().getManager("entity");
			Resource parent = (Resource) entitymanager.getObject(parentID);
			parent.addChild(this);
			parent.update();
			entitymanager.add(this);
			parentID = null;
		}
		this.attributes.putAll(attrs);
		// 如果应该更新数据库
		if (isShouldUpdate()) {
			this.update();
		}
	}

	public void addUser(User user) throws Exception {
		user.addRole(this);
		user.updateRolesList();
	}

	/**
	 * 扩充addUser方法，以使用于北京项目
	 */
	public void add(User user) throws Exception {
		this.addUser(user);
	}

	public void remove(User user) throws Exception {
		user.removeRole(this);
		user.updateRolesList();
	}

	public LinkedList getUsers() {
		LinkedList result = new LinkedList();
		// 找到所有包含该角色的用户
		LinkedList list = EntityManager.getInstance().getUsers();
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			User user = (User) iter.next();
			if (user.getRoles().contains(this)) {
				result.add(user);
			}
		}
		return result;
	}

	public Iterator getChildren() {
		LinkedList result = new LinkedList();
		// 找到所有包含该角色的用户
		LinkedList list = EntityManager.getInstance().getUsers();
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			User user = (User) iter.next();
			if (user.getRoles().contains(this)) {
				result.add(user);
			}
		}
		return result.iterator();
	}

	/**
	 * 将用户列表中的用户添加到组中去
	 */
	public void addUser(LinkedList list) throws Exception {
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			User user = (User) iter.next();
			user.addRole(this);
			user.updateRolesList();
		}
	}

	/**
	 * 得到角色所拥有的所有功能
	 */
	public LinkedList getFunctions() {
		return functions;
	}

	/**
	 * 给角色添加功能
	 */
	public void add(Function func) {
		functions.add(func);
	}

	/**
	 * 从角色中移走功能
	 */
	public void remove(Function func) {
		functions.remove(func);
	}

	/**
	 * 给角色设置功能并修改相应的数据库
	 */
	public void setFunctions(LinkedList v) throws Exception {
		// 删除功能包含的角色
		for (int i = 0; i < functions.size(); i++) {
			((Function) functions.get(i)).remove(this);
		}
		this.functions = v;
		// 给功能增加角色
		for (int i = 0; i < functions.size(); i++) {
			((Function) functions.get(i)).add(this);
		}
		DBTools.excuteUpdate("delete from T_function_role where role_id="
				+ this.getAttributes().get("id"));
		for (int i = 0; i < v.size(); i++) {
			DBTools.excuteUpdate("insert into T_function_role(role_id,function_id) values("
					+ this.getAttributes().get("id")
					+ ","
					+ ((Function) v.get(i)).getAttributes().get("id") + ")");
		}
	}

	/**
	 * 记录客户端环境
	 * 
	 * @param request
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.action = request.getParameter("action");
	}

	/**
	 * 取得选项值列表
	 */
	public Iterator getOptions(String selectName) {
		return null;
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
		super.setComponent(component);
		this.component = component;
	}

	/**
	 * 模型更新页面元素
	 * 
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	public boolean isUser(LinkedList us) throws Exception {
		for (int i = 0; i < us.size(); i++) {
			EntityManager entitymanager = (EntityManager) ManagerGroup
					.getManagerGroup().getManager("entity");
			Resource res = (Resource) entitymanager.getObject((String) us
					.get(i));
			if (!(res instanceof User)) {
				Element e = (Element) this.component.getPage().getDocument()
						.getElementsByTagName("body").item(0);
				e.setAttribute("onload", "alert('必须全部选择人员，不能选择其它资源')");
				return false;
			}
		}
		return true;
	}

	public String getTableName() {
		return "t_role";
	}

	/**
	 * 判断该用户是否属于这个角色 user用户
	 */
	public boolean isRoleContainUser(User user) {
		return user.getRoles().contains(this);
	}

	/**
	 * 看是否需要插入
	 * 
	 * @return 是否需要插入
	 */
	protected boolean isShouldInsert() {
		// 如果有action
		Element e = this.component.getElement();
		Iterator iter = ExtendElement.findElements(e, "name", "action")
				.iterator();
		if (iter.hasNext()) {
			// 如果有parentID,并且action的值为"confirm"
			if (parentID != null && !parentID.equals("") && action != null
					&& action.equals("confirm")) {
				return true;
			}
		}
		// 否则,如果有parentID
		else if (parentID != null && !parentID.equals("")) {
			return true;
		}
		return false;
	}

	/**
	 * 是否应该更新数据库
	 * 
	 * @return 是否应该更新数据库
	 */
	protected boolean isShouldUpdate() {
		// 如果页面有action
		Element e = this.component.getElement();
		Iterator iter = ExtendElement.findElements(e, "name", "action")
				.iterator();
		if (iter.hasNext()) {
			// 如果action的值不为"confirm"
			if (action == null || !action.equals("confirm")) {
				return false;
			}
		}
		return true;
	}

	public void sychronUpdate(Hashtable attributes) {
		super.sychronUpdate(attributes);
	}

	protected void deleteRelation() {
		super.deleteRelation();
	}
}